import router from './router/index'
import { useUserStore } from './store/index'
import { storeToRefs } from 'pinia'
import { upperFirst } from './utils/stringUtil';

import NProgress from "nprogress";
import "nprogress/nprogress.css";

NProgress.configure({ showSpinner: false }); // 进度条

const modules = import.meta.glob("./views/**/**.vue");
//白名单
const noLimitPages = [
    { path: "index", title:"智慧社区", component: "home/IndexView.vue" },
    { path: "/newsadd/:id", title:"添加新闻", component: "news/Add.vue" },
    { path: "/stores/:id", title:"添加图片", component: "stores/AddView.vue" },
    // { path: "/hook", title:"hookUse", component: "test/hookUse.vue" },
]
//路由前置守卫 
router.beforeEach((to) => {
    console.log("3232");
    //进度条开始加载
    NProgress.start();
    //如果是登录页面 不做任何处理
    if (to.path === "/login") {
        return;
    }
    const store = useUserStore();
    //从pinia读取token和权限
    let { token, menus } = storeToRefs(store);
    //用户未登录 跳转到登录页面
    if (!token.value) {
        return "/login";
    }
    else {
        //用户登录 添加动态路由
        // 如果动态路由未创建 则创建动态
        if (router.getRoutes().length === 3) {
            //添加白名单的路由
            noLimitPages.forEach((item:any) => {
                router.addRoute("Home", {
                    path: item.path,
                    name: item.path,
                    meta:{title:item.title},
                    component: modules[`./views/${item.component}`]
                });
            })
            //获取用户权限
            let _menus = menus.value.filter((item: any) => item.url);
            _menus.forEach((element: any) => {
                //因为element.url首字母小写 把首字母变大写
                let url = upperFirst(element.url.replace("/", ""));
                let component = modules[`./views${element.url}/${url}View.vue`];
                if (!component) component = modules[`./views/404.vue`];
                router.addRoute("Home", {
                    path: element.url,
                    name: element.url,
                    meta:{title:element.name},
                    component: component
                });
            });
            return to.fullPath;
        }
        
        
    }
    console.log("3232");

})
//路由后置守卫
router.afterEach((to:any)=>{
    //进度条结束
    console.log("当期页面",to);
    document.title=to.meta.title ?? "智慧社区";
    NProgress.done();
})